package com.keyue.isolate.config;


import com.fasterxml.jackson.core.type.TypeReference;
import com.keyue.common.utils.JsonUtil;
import com.keyue.isolate.context.IsolateTableConfigVO;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.core.io.ResourceLoader;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 数据隔离V2配置类
 * 监听nacos json格式配置文件
 * 由于nacos枚提供基于json的ConfigurationProperties,故手动注册nacos配置监听器
 * 监听 CONFIG_FILE_ID 配置文件的变化
 *
 * @author fanzhenyu
 * @Date 2025/04/29
 */
@Data
@Slf4j
@Component
public class DataIsolateGlobalRefreshConfig implements InitializingBean {

    private static final String CONFIG_FILE_ID = "/data-isolate-config.json";

    @Resource
    private ResourceLoader resourceLoader;


    private static Map<String, List<IsolateTableConfigVO>> tableName2Configs = new HashMap<>();

    public List<IsolateTableConfigVO> findConfigsByTableName(String tableName) {
        return Collections.unmodifiableList(tableName2Configs.getOrDefault(tableName, Collections.emptyList()));
    }

    @Override
    public void afterPropertiesSet() {

        try {
            String dataIsolateV2ConfigJson = IOUtils.toString(getClass().getResourceAsStream(CONFIG_FILE_ID), "UTF-8");

            refreshConfig(dataIsolateV2ConfigJson);
        } catch (Exception e) {
            log.error("初始化 DataIsolateGlobalConfig 异常", e);
            throw new RuntimeException("config 配置 异常");
        }


    }

    private static void refreshConfig(String dataIsolateV2ConfigJson) {
        Map<String, List<IsolateTableConfigVO>> newConfigs = JsonUtil.jsonToEntity(dataIsolateV2ConfigJson, new TypeReference<Map<String, List<IsolateTableConfigVO>>>() {
        });
        if (null == newConfigs) {
            log.error("DataIsolateGlobalRefreshConfig刷新配置失败,请检查配置文件格式");
            return;
        }
        tableName2Configs = newConfigs;
    }

}
